package com.huikeportal.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.huike.model.MsgResponse;
import com.huike.tools.DateTool;
import com.huike.tools.MessageTool;
import com.huikeportal.model.AspnetUsers;
import com.huikeportal.model.ReportGraphData;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.WordBook;
import com.huikeportal.model.common.InterFaceModel;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.CommonService;
import com.huikeportal.service.FootfallGlobalService;
import com.huikeportal.service.InterFaceCommon;
import com.huikeportal.service.LoginService;
import com.huikeportal.service.SelectSiteService;


@Controller

public class ComparativeAnalysisAPI {
	
	
	@Autowired
	private FootfallGlobalService footfallGlobalService;
	
	@Autowired
	private InterFaceCommon interFaceCommon;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private LoginService loginService;
	
	@Autowired
	SelectSiteService selectSiteService;
	/**
	 * 对比分析的指标
	 * @throws Exception 
	 */
	@RequestMapping(value = "/huike_getComparativeIndex", produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String getComparativeIndex(String userId, String siteId, String moduleId){
		
		// 接口记录对象
		InterFaceModel interFaceModel = new InterFaceModel();
		// 接口名称
		interFaceModel.setInterName("huike_getComparativeIndex");
		// 接口开始时间
		interFaceModel.setStartTime(DateTool.getDateYmdHms());
		// 返回对象
		MsgResponse msgResponse = new MsgResponse();
		/**
		 * start Validate
		 */
		//1、是否为空验证、参数合法性验证
		StringBuffer reMassege = new StringBuffer();
		UserInfo userInfo = new UserInfo();
		userInfo.setUserId(userId);
		if(userId == null || "".equals(userId)){
			reMassege.append("userId为空错误;");
		}else{
			try {
				AspnetUsers aspnetUsers = commonService.getaspnetUsersMapper(userInfo);
				if(aspnetUsers == null){
					reMassege.append("userId不合法;");
				}
			} catch (Exception e) {
				reMassege.append("userId不合法;");
			}
		}
		if(siteId == null || "".equals(siteId)){
			reMassege.append("siteId为空错误;");
		}else{
			String retSiteInfo	= footfallGlobalService.getSiteAllInfoById(siteId);
			if(retSiteInfo.length() > 0){
				reMassege.append("siteId不合法,"+retSiteInfo+";");
			}
		}
		if(moduleId == null || "".equals(moduleId)){
			reMassege.append("moduleId为空错误;");
		}
		//如果验证有错误返回错误信息
		if(reMassege.length()>0){
			msgResponse.setRespCode("90003");
			msgResponse.setRespCodeDes(MessageTool.RESP_90003);
			msgResponse.setObject(reMassege.toString());
			// 接口结束时间
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			// 接口状态
			interFaceModel.setInterStatus("success");
			// 记录接口调用情况
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}
		/**
		 * end  Validate
		 */
		
		/**
		 * start service
		 */
		try{
			/**初始化指标权限*/
	        List<String> siteTypes = footfallGlobalService.getSiteTypes(siteId);
	        /**获取用户指标权限*/
	        List<String> userIndexList = footfallGlobalService.getUserIndex(userInfo);
	        /**指标为场所指标和用户指标交集*/
	        //获取趋势分析指标
	        List<String> indexList = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId, siteTypes);
	        //取趋势分析指标分组
	        HashMap<String, List<String>> indexListOfGroup = footfallGlobalService.getIndexListOfGroup(indexList);
	        HashMap<String, Object> resutMap = new HashMap<String, Object>();
	        resutMap.put("indexList",JSONObject.fromObject(indexListOfGroup));
	        
	      //获取排行榜各时间指标
	        HashMap<String, Object> dateIndexMap = new HashMap<String, Object>();
	        List<String> indexHour  = footfallGlobalService.getTimeIndex("hour");
	        dateIndexMap.put("indexHour", indexHour);
	        List<String> indexDay  = footfallGlobalService.getTimeIndex("day");
	        dateIndexMap.put("indexDay", indexDay);
	        List<String> indexWeek  = footfallGlobalService.getTimeIndex("week");
	        dateIndexMap.put("indexWeek", indexWeek);
	        List<String> indexMonth  = footfallGlobalService.getTimeIndex("month");
	        dateIndexMap.put("indexMonth", indexMonth);
	        List<String> indexYear  = footfallGlobalService.getTimeIndex("year");
	        dateIndexMap.put("indexYear", indexYear);
	        resutMap.put("dateIndexMap",JSONObject.fromObject(dateIndexMap));
	
	        HashMap<String, String>  indexGroupInfo = footfallGlobalService.getIndexGroupInfo();
	        resutMap.put("indexGroupInfo",JSONObject.fromObject(indexGroupInfo));
	        HashMap<String, String>  indexInfo = footfallGlobalService.getIndexInfo();
	        resutMap.put("indexInfo",JSONObject.fromObject(indexInfo));
	        /**初始化全局分析的指标权限结束*/
	        
	        msgResponse.setRespCode("90001");
			msgResponse.setRespCodeDes(MessageTool.RESP_90001);
			msgResponse.setObject(resutMap);
			// 接口结束时间
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			// 接口状态
			interFaceModel.setInterStatus("success");
			// 记录接口调用情况
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}catch (Exception e) {
			e.printStackTrace();
			msgResponse.setRespCode("90002");
			msgResponse.setRespCodeDes(MessageTool.RESP_90002);
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			interFaceModel.setInterStatus("failure");
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}
		/**
		 * end service
		 */
	}
	
	/**前台获取图表数据  */

	@RequestMapping(value = "/huike_getComparativeAnalysis", produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String getGraphData(String userId, String siteId, String type,String span,String from,String to) throws Exception {
		
		
		// 接口记录对象
		InterFaceModel interFaceModel = new InterFaceModel();
		// 接口名称
		interFaceModel.setInterName("huike_getComparativeAnalysis");
		// 接口开始时间
		interFaceModel.setStartTime(DateTool.getDateYmdHms());
		// 返回对象
		MsgResponse msgResponse = new MsgResponse();
		
		/**
		 * start Validate
		 */
		//1、是否为空验证、参数合法性验证
		StringBuffer reMassege = new StringBuffer();
		//userId验证
		UserInfo userInfo = new UserInfo();
		userInfo.setUserId(userId);
		if(userId == null || "".equals(userId)){
			reMassege.append("userId为空错误;");
		}else{
			try {
				AspnetUsers aspnetUsers = commonService.getaspnetUsersMapper(userInfo);
				if(aspnetUsers == null){
					reMassege.append("userId不合法;");
				}
			} catch (Exception e) {
				reMassege.append("userId不合法;");
			}
		}
		//siteId验证
		if(siteId == null || "".equals(siteId)){
			reMassege.append("siteId为空错误;");
		}
		//type验证
		if(type == null || "".equals(type)){
			reMassege.append("type为空错误;");
		}else{
			HashMap<String, String>  indexInfo = footfallGlobalService.getIndexInfo();
			String typeName = indexInfo.get(type);
			if(typeName == null || "".equals(typeName)){
				reMassege.append("type不合法,"+type+";");
			}
		}
		//span验证
		if(span == null || "".equals(span)){
			reMassege.append("span为空错误;");
		}else{
			Pattern  pattern = Pattern.compile("^hour_(0|1|2)$|^day_(0|1|7|14|30)$|^week_(0|4|8|12)$|^month_(0|3|6|12)$|^year_(0|3|5)$|");
			Matcher  matcher = pattern.matcher(span);
			if(!matcher.matches()){
				reMassege.append("span不合法,"+span+";");
			}
			String[] Strings =span.split("_");
			//from验证
			if("0".equals(Strings[1])){
				if(from == null || "".equals(from)){
					reMassege.append("from为空错误,");
				}else{
					if(!commonService.isDateStr(from)){
						reMassege.append("from不合法,"+from+";");
					}
				}
				//to验证
				if(to == null || "".equals(to)){
					reMassege.append("to为空错误,");
				}else{
					if(!commonService.isDateStr(to)){
						reMassege.append("to不合法,"+to+";");
					}
				}
				if(commonService.isDateStr(to) && commonService.isDateStr(from)){
					SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
					Date fromDate = sdf.parse(from);
					Date toDate = sdf.parse(to);
					if(fromDate.after(toDate)){
						reMassege.append("from大于to错误,"+"from="+from+"to="+to+";");
					}
				}
				
			}
		}
		//如果验证有错误返回错误信息
		if(reMassege.length()>0){
			msgResponse.setRespCode("90003");
			msgResponse.setRespCodeDes(MessageTool.RESP_90003);
			msgResponse.setObject(reMassege.toString());
			// 接口结束时间
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			// 接口状态
			interFaceModel.setInterStatus("success");
			// 记录接口调用情况
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}
		
		/**
		 * end  Validate
		 */
		
		/**
		 * start service
		 */
		try{
			String[] Strings =span.split("_");
			//日周月年
			String timeType_table=Strings[0];
			//类型，7、14、30天；4、8、12周；3、6、12月；3、5年
			String timeType=Strings[1];
			String[] siteIds = siteId.split(",");
			
			HashMap<String , Object> paraMapResult=new HashMap<String, Object>();
			//查询图表
			List<HashMap<String, Object>> resultList=new ArrayList<HashMap<String, Object>>();
			HashMap<String , Object> paraMap=new HashMap<String, Object>();
			paraMap.put("timeType", timeType);
			paraMap.put("timeType_table", timeType_table);//日周月年表
			paraMap.put("startDate", from);
			paraMap.put("endDate", to);
			paraMap.put("type", type);
			paraMap.put("userInfo", userInfo);
			
			List<String> siteNames =  new ArrayList<String>();//导航栏地址
			List<ReportGraphData> listNames = new ArrayList<ReportGraphData>() ;
			for(int n=0;n<siteIds.length;n++){
				if(!"".equals(siteIds[n])){
					siteNames.add(footfallGlobalService.getSiteNames(siteIds[n]));//导航栏地址
				}
				paraMap.put("siteId", siteIds[n]);
				List<ReportGraphData> list= footfallGlobalService.getGraphData(paraMap);
				listNames = list;
				String siteName=footfallGlobalService.getSiteName(siteIds[n]);
				HashMap<String, Object> map=new HashMap<String, Object>();
				map.put("data",list);
				map.put("siteId",siteIds[n]);
				map.put("siteName",siteName);
				resultList.add(map);
			}
			//报表数据说明
			String sitenames = "";
			if("hour".equals(timeType_table)){
				if(listNames.size()==0){
					paraMapResult.put("",from);
				}else{
					paraMapResult.put("stadubiao", listNames.get(0).getDate());	
				}
			}else if("day".equals(timeType_table)){
				paraMapResult.put("stadubiao", listNames.get(0).getDatatime());
				paraMapResult.put("endtubiao", listNames.get(listNames.size()-1).getDatatime());
			}else if("week".equals(timeType_table)){
				paraMapResult.put("stadubiao", listNames.get(0).getYear()+"-"+listNames.get(0).getWeek());
				paraMapResult.put("endtubiao", listNames.get(listNames.size()-1).getYear()+"-"+listNames.get(listNames.size()-1).getWeek());
			}else if("month".equals(timeType_table)){
				paraMapResult.put("stadubiao", listNames.get(0).getYear()+"-"+listNames.get(0).getMonth());
				paraMapResult.put("endtubiao", listNames.get(listNames.size()-1).getYear()+"-"+listNames.get(listNames.size()-1).getMonth());
			}else{
				paraMapResult.put("stadubiao", listNames.get(0).getYear());
				paraMapResult.put("endtubiao", listNames.get(listNames.size()-1).getYear());
			}
			if(siteNames.size()<4){
				for(String sitename:siteNames){
					sitenames = sitenames +sitename+'，';
				}
				if(!"".equals(sitenames)){
					sitenames = sitenames.substring(0, sitenames.length()-1);
				}
			}else{
				int i = 0;
				for(String sitename:siteNames){
					if(i>=3){
						break;
					}
					sitenames = sitenames +sitename+'，';
					i++;
				}
				sitenames = sitenames.substring(0, sitenames.length()-1);
				sitenames = sitenames+"．．．";
			}
			String siteTypeNames = "";
			String[] siteidstr = siteId.split(",");
			for(String siteid:siteidstr){
				String siteName = footfallGlobalService.getSiteNames(siteid);
				//获取siteId 的场所类型中文名称
				siteTypeNames = siteTypeNames + siteName+"&";
			}
			siteTypeNames = siteTypeNames.substring(0, siteTypeNames.length()-1);
			
			paraMapResult.put("siteTypeNames", siteTypeNames);
			
			paraMapResult.put("siteN", sitenames);
			//插入数据日期类型，日周年月
			paraMapResult.put("timeType_table",timeType_table);
			//插入折线数据
			paraMapResult.put("result", resultList);
			//获取表格数据
			StringBuffer loadTable = footfallGlobalService.getGlobalTable(resultList,timeType_table,type);
			paraMapResult.put("loadTable", loadTable.toString());
			/**
			 *  end 取数据
			 */
		 	msgResponse.setRespCode("90001");
			msgResponse.setRespCodeDes(MessageTool.RESP_90001);
			msgResponse.setObject(paraMapResult);
			// 接口结束时间
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			// 接口状态
			interFaceModel.setInterStatus("success");
			// 记录接口调用情况
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}catch (Exception e) {
			msgResponse.setRespCode("90002");
			msgResponse.setRespCodeDes(MessageTool.RESP_90002);
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			interFaceModel.setInterStatus("failure");
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}
		/**
		 * end service
		 */
		
	}

	
	/**
	 * 判断是否是测试账号
	 * @throws Exception 
	 */
	@RequestMapping(value = "/huike_ifTestAcount", produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String ifTestAcount(String userId){
		
		// 接口记录对象
		InterFaceModel interFaceModel = new InterFaceModel();
		// 接口名称
		interFaceModel.setInterName("huike_ifTestAcount");
		// 接口开始时间
		interFaceModel.setStartTime(DateTool.getDateYmdHms());
		// 返回对象
		MsgResponse msgResponse = new MsgResponse();
		/**
		 * start Validate
		 */
		//1、是否为空验证、参数合法性验证
		StringBuffer reMassege = new StringBuffer();
		UserInfo userInfo = new UserInfo();
		userInfo.setUserId(userId);
		AspnetUsers aspnetUsers = new AspnetUsers();
		if(userId == null || "".equals(userId)){
			reMassege.append("userId为空错误;");
		}else{
			try {
				aspnetUsers = commonService.getaspnetUsersMapper(userInfo);
				if(aspnetUsers == null || aspnetUsers.getUserid() == null || "".equals(aspnetUsers.getUserid())){
					reMassege.append("userId不合法;");
				}
			} catch (Exception e) {
				reMassege.append("userId不合法;");
			}
		}
		//如果验证有错误返回错误信息
		if(reMassege.length()>0){
			msgResponse.setRespCode("90003");
			msgResponse.setRespCodeDes(MessageTool.RESP_90003);
			msgResponse.setObject(reMassege.toString());
			// 接口结束时间
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			// 接口状态
			interFaceModel.setInterStatus("success");
			// 记录接口调用情况
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}
		/**
		 * end  Validate
		 */
		
		/**
		 * start service
		 */
		try{
			String userName = aspnetUsers.getUsername();
	        String juge = getUpperUser(userName);
			HashMap<String , String> paraMap=new HashMap<String, String>();
			paraMap.put("juge",juge);
	        msgResponse.setRespCode("90001");
			msgResponse.setRespCodeDes(MessageTool.RESP_90001);
			msgResponse.setObject(paraMap);
			// 接口结束时间
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			// 接口状态
			interFaceModel.setInterStatus("success");
			// 记录接口调用情况
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}catch (Exception e) {
			msgResponse.setRespCode("90002");
			msgResponse.setRespCodeDes(MessageTool.RESP_90002);
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			interFaceModel.setInterStatus("failure");
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}
		/**
		 * end service
		 */
	}
	
	private String getUpperUser(String createUserId) throws Exception {
		String juge = "1";
		String userName = createUserId;
		UserInfo userInfo = new UserInfo();
		userInfo.setUserName(userName);
        userInfo = loginService.getUserInfo(userInfo); //得到用户信息
        if(userInfo==null){
        	return juge;
        }
        String createUser = userInfo.getCreateUserId();
        String user = userInfo.getUserName();
        if("jituan".equals(createUser)||"jituan".equals(user)){
        	juge = "0";
        }else if(createUser != null && !"".equals(createUser)){
        	juge = getUpperUser(createUser);
        }
		return juge;
	}
	
	
	/**
	 * 获取有权限按钮列表
	 * @throws Exception 
	 */
	@RequestMapping(value = "/huike_getUserButtonList", produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String getUserButtonList(String userId,String modelName,String sysLang){
		
		// 接口记录对象
		InterFaceModel interFaceModel = new InterFaceModel();
		// 接口名称
		interFaceModel.setInterName("huike_getUserButtonList");
		// 接口开始时间
		interFaceModel.setStartTime(DateTool.getDateYmdHms());
		// 返回对象
		MsgResponse msgResponse = new MsgResponse();
		/**
		 * start Validate
		 */
		//1、是否为空验证、参数合法性验证
		StringBuffer reMassege = new StringBuffer();
		UserInfo userInfo = new UserInfo();
		userInfo.setUserId(userId);
		AspnetUsers aspnetUsers = new AspnetUsers();
		if(userId == null || "".equals(userId)){
			reMassege.append("userId为空错误;");
		}else{
			try {
				aspnetUsers = commonService.getaspnetUsersMapper(userInfo);
				if(aspnetUsers == null || aspnetUsers.getUserid() == null || "".equals(aspnetUsers.getUserid())){
					reMassege.append("userId不合法;");
				}
			} catch (Exception e) {
				reMassege.append("userId不合法;");
			}
		}
		//模块url
		SqlParameter sql = new SqlParameter();
        sql.setSysLang(sysLang);
        sql.setString(modelName);
        Integer menuId = -1;
		if(modelName == null || "".equals(modelName)){
			reMassege.append("modelName为空错误;");
		}else{
			try {
		        menuId = selectSiteService.getMenuId(sql);
		        if(menuId == null || menuId == -1){
					reMassege.append("modelName不合法;");
				}
			} catch (Exception e) {
				reMassege.append("modelName不合法;");
			}
		}
		//如果验证有错误返回错误信息
		if(reMassege.length()>0){
			msgResponse.setRespCode("90003");
			msgResponse.setRespCodeDes(MessageTool.RESP_90003);
			msgResponse.setObject(reMassege.toString());
			// 接口结束时间
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			// 接口状态
			interFaceModel.setInterStatus("success");
			// 记录接口调用情况
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}
		/**
		 * end  Validate
		 */
		/**
		 * start service
		 */
		try{
			   //获取用户权限按钮信息
	        List<WordBook> buttonList = loginService.getUserButtonList(sysLang,
	                userId, menuId);
			HashMap<String , List<WordBook>> paraMap=new HashMap<String, List<WordBook>>();
			paraMap.put("buttonList",buttonList);
	        msgResponse.setRespCode("90001");
			msgResponse.setRespCodeDes(MessageTool.RESP_90001);
			msgResponse.setObject(paraMap);
			// 接口结束时间
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			// 接口状态
			interFaceModel.setInterStatus("success");
			// 记录接口调用情况
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}catch (Exception e) {
			msgResponse.setRespCode("90002");
			msgResponse.setRespCodeDes(MessageTool.RESP_90002);
			interFaceModel.setEndTime(DateTool.getDateYmdHms());
			interFaceModel.setInterStatus("failure");
			interFaceCommon.logInterface(interFaceModel);
			return JSONObject.fromObject(msgResponse).toString();
		}
		/**
		 * end service
		 */
	}
	
	
	

}
